package com.cskaoyan.service.impl;

import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.PageParameter;
import com.cskaoyan.mapper.MarketLogMapper;
import com.cskaoyan.model.MarketAdmin;
import com.cskaoyan.model.MarketLog;
import com.cskaoyan.model.MarketLogExample;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.service.LogService;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.MyBatisUtil;
import com.cskaoyan.utils.TransactionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

public class LogServiceImpl implements LogService {
    AuthService authService = new AuthServiceImpl();

    @Override
    public void insertLog(HttpServletRequest request, Integer type, String action, Boolean status, String result, String comment) {
        MarketLogMapper logMapper = TransactionUtil.getMapper(MarketLogMapper.class);
        HttpSession session = request.getSession();
        Integer adminId = (Integer) session.getAttribute(Constant.ADMIN_KEY);
        MarketAdmin admin = authService.findById(adminId);
        MarketLog log = MarketLog.builder()
                .admin(admin.getUsername())
                .ip(request.getRemoteAddr())
                .type(type)
                .action(action)
                .status(status)
                .result(result)
                .comment(comment)
                .addTime(new Date())
                .updateTime(new Date())
                .deleted(false).build();
        logMapper.insert(log);
    }

    @Override
    public PageData list(PageParameter pageParameter, String name) {
        //1. 为mybatis做分页+条件查询构造条件
        //1.1 page、limit做分页，使用分页插件
        PageHelper.startPage(pageParameter.getPage(), pageParameter.getLimit());
        //1.2 通过example构造条件：sort、order做排序
        MarketLogExample example = new MarketLogExample();
        example.setOrderByClause(pageParameter.getSort() + " " + pageParameter.getOrder());
        //1.3 增加条件，那些没有被删除的
        MarketLogExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        //1.4 增加条件，前端传过来的请求参数中的name，首先判断是否为空
        if (name != null) {
            criteria.andAdminLike("%" + name + "%");
        }

        //2. 根据前端传来的参数，用mybatis来查询数据库中的数据作为data中的list
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketLogMapper logMapper = sqlSession.getMapper(MarketLogMapper.class);
        List<MarketLog> marketLogs = logMapper.selectByExample(example);

        //3. 将这list数据封装PageData，这里调用PageData中的list()方法即可，
        // 因为这样也可以通过分页插件中的pageInfo给pageData中的其他参数赋值
        PageData pageData = PageData.list(marketLogs);

        //4. 返回pageData作为响应报文中的data数据
        return pageData;
    }
}
